package leetcode;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * @program: datastructureandalogorithm
 * @description:
 * @author: hmx
 * @create: 2022-01-06 00:21
 **/
public class LeetCode71 {

    public String simplifyPath(String path) {
        //根据'/'分隔路径
        String[] paths = path.split("/");
        Deque<String> deque = new ArrayDeque<>();
        for (String word : paths) {
            //如果被分割的路径中有..说明需要跳到到上级目录,所以弹出当前目录
            if ("..".equals(word)) {
                deque.pollLast();
            } else if (word.length() > 0 && !".".equals(word)) {
                //如果是一个空字符串""或者是".",都不用处理,空字符串说明是开头或者多个连续的"/","."说明是当前目录,也可以优化掉,只处理正常的目录情况,将目路添加到队尾
                deque.offer(word);
            }
        }

        //拼接优化后的路径
        StringBuilder builder = new StringBuilder();
        //如果队列为空,说明path只由"/"或者"./"组成,直接返回"/"
        if (deque.isEmpty()) {
            builder.append('/');
        } else {
            while (!deque.isEmpty()) {
                builder.append('/');
                builder.append(deque.poll());
            }
        }

        return builder.toString();
    }

}
